package com.lml.jdk8.localdate.java8Time;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;

/**
 * @author luomingliang
 * @date 2021/9/12 21:28
 */
public class TestQueryImpl implements TemporalQuery<Long[]> {
    /*
     * 需求：计算任意时间与下一个圣诞节/儿童节/劳动节各相差多少天？
     */

    /**
     * 查询任意时间与下一个圣诞节/儿童节/劳动节各相差多少天
     *
     * @param temporal 日期
     * @return 表示距离三个节日的天数差额，0索引表示距离圣诞节，1索引表示距离儿童节，2索引表示距离劳动节
     */
    @Override
    public Long[] queryFrom(TemporalAccessor temporal) {
        LocalDate date = LocalDate.from(temporal);
        //1.分别获取当年的圣诞节/儿童节/劳动节的具体日期
        LocalDate christmasDay = LocalDate.of(date.getYear(), Month.DECEMBER, 25);
        LocalDate childrenDay = LocalDate.of(date.getYear(), Month.JUNE, 1);
        LocalDate laborDay = LocalDate.of(date.getYear(), Month.MAY, 1);
        //2.分别判断localdate与3个节日的前后关系，如果localdate已超过某个节日，则获取距离下一年该节日的天数
        if (date.isAfter(christmasDay)) {
            christmasDay = christmasDay.plusYears(1);
        }
        if (date.isAfter(childrenDay)) {
            childrenDay = childrenDay.plusYears(1);
        }
        if (date.isAfter(laborDay)) {
            laborDay = laborDay.plusYears(1);
        }
        return new Long[]{ChronoUnit.DAYS.between(date, christmasDay),
                ChronoUnit.DAYS.between(date, childrenDay),
                ChronoUnit.DAYS.between(date, laborDay)};
    }

    //测试
    public static void main(String[] args) {
        //1.封装任意日期
        LocalDate date = LocalDate.of(2020, 5, 30);
        //2.调用date对象的query方法来查询距离三个节日的差额
        Long[] longs = date.query(new TestQueryImpl());
        //3.打印结果
        System.out.println("当前时间为：" + date);
        System.out.println("距离下一个圣诞节还有" + longs[0] + "天");
        System.out.println("距离下一个儿童节还有" + longs[1] + "天");
        System.out.println("距离下一个劳动节还有" + longs[2] + "天");
    }
}
